package cn.com.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import cn.com.api.entity.ApiT_member;

/**
 * 公众平台通用接口工具类
 * 
 */
public class WeixinUtil {

	private static Logger logger = LogManager.getLogger(WeixinUtil.class.getName());

	// APPID
	public static String appId = "wx31b38c7aa4d32f2c";
	// public static String appId = "wx73703c78af59a6c7";
	// secret
	public static String secret = "e8d129efba6b59a04f94c05d8a2fd27c";
	// public static String secret = "4446ae37d73646d223d68292fb50e653";

	private static String partner = "1270138701";

	public static String key = "a8b9050fd3d357f75c4d4e8d253cec63";// API密钥

	// 账户全局变量
	public static String access_token = "";
	public static String jsapi_ticket = "";
	private static String weixin_notify = "http://uj345.com/B2C4Upai/mobile/weixin_notify";

	// 获取access_token的接口地址（GET） 限200（次/天）
	public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
	// 获取jsapi_ticket的接口地址（GET）
	public final static String jsapi_ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
	// 创建菜单
	public final static String menu = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
	// 同意用户授权获取code
	public final static String codeUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=URL&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
	// 获取openid
	public final static String openIdUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

	// 获取用户基本信息
	public final static String user_info = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";

	// 获取用户基本信息
	public final static String user_info2 = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";

	/**
	 * 获取access_token
	 * 
	 * @param appid
	 *            凭证
	 * @param appsecret
	 *            密钥
	 * @return
	 */
	public static void getAccessToken(String appid, String appsecret) {
		String requestUrl = access_token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
		JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
		// 如果请求成功
		if (null != jsonObject) {
			try {
				access_token = jsonObject.getString("access_token");
			} catch (JSONException e) {
				access_token = null;
				// 获取token失败
				logger.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"),
						jsonObject.getString("errmsg"));
			}
		}
	}

	/**
	 * 获取openid
	 * 
	 * @param appid
	 *            凭证
	 * @param appsecret
	 *            密钥
	 * @return
	 */
	public static Map<String, String> getOpenId(String appid, String appsecret, String code) {
		String requestUrl = openIdUrl.replace("APPID", appid).replace("SECRET", appsecret).replace("CODE", code);
		JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
		// 如果请求成功
		if (null != jsonObject) {
			try {
				Map<String, String> map = new HashMap<String, String>();
				map.put("access_token", jsonObject.getString("access_token"));
				map.put("openid", jsonObject.getString("openid"));
				System.out.println("access_token:" + jsonObject.getString("access_token") + ";openid:"
						+ jsonObject.getString("openid"));
				return map;
			} catch (JSONException e) {
				// 获取token失败
				logger.error("获取openid失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"),
						jsonObject.getString("errmsg"));
				System.out.println("获取openid失败 errcode:{} errmsg:{}" + jsonObject.getInt("errcode") + "+++++"
						+ jsonObject.getString("errmsg"));
			}
		}
		return null;
	}

	/**
	 * 获取jsapi_ticket
	 * 
	 * @param appid
	 *            凭证
	 * @param appsecret
	 *            密钥
	 * @return
	 */
	public static void getJsapiTicket() {
		String requestUrl = jsapi_ticket_url.replace("ACCESS_TOKEN", access_token);
		JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
		// 如果请求成功
		if (null != jsonObject) {
			try {
				jsapi_ticket = jsonObject.getString("ticket");
			} catch (JSONException e) {
				jsapi_ticket = null;
				// 获取jsapi_ticket失败
				logger.error("获取jsapi_ticket失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"),
						jsonObject.getString("errmsg"));
			}
		}
	}

	/**
	 * 微信统一支付参数
	 * 
	 * @return map
	 */
	public static Map<String, String> getPrepayId(HttpServletRequest request, Map<String, String> par) {
		Map<String, String> map = new HashMap<String, String>();
		String noncestr = Random.randomStr();
		// String timestamp = Random.longtime();
		map.put("appid", WeixinUtil.appId);
		map.put("body", par.get("body"));
		map.put("mch_id", WeixinUtil.partner);
		map.put("nonce_str", noncestr);
		// map.put("timestamp", timestamp);
		map.put("out_trade_no", par.get("out_trade_no"));
		map.put("spbill_create_ip", request.getRemoteHost());
		map.put("total_fee", par.get("total_fee"));
		map.put("notify_url", WeixinUtil.weixin_notify);
		ApiT_member member = (ApiT_member) request.getSession().getAttribute("mobile_webuser");
		map.put("openid", member.getOpenid());
		map.put("trade_type", "JSAPI");
		String sign = SignUtil.createLinkString(map, key);
		map.put("sign", sign);
		return HttpPostUtil.payPost(map);
	}

	/**
	 * 微信jsapi支付参数
	 * 
	 * @return map
	 */
	public static Map<String, String> getJSAPIPar(String prepayId) {
		Map<String, String> map = new HashMap<String, String>();
		String timestamp = Random.longtime();
		String noncestr = Random.randomStr();
		map.put("appId", WeixinUtil.appId);
		map.put("timeStamp", timestamp);
		map.put("nonceStr", noncestr);
		map.put("package", "prepay_id=" + prepayId);
		map.put("signType", "MD5");
		String sign = SignUtil.createLinkString(map, key);
		map.put("paySign", sign);
		return map;
	}

	/**
	 * 获取openid
	 * 
	 * @param appid
	 * @return
	 */
	public static Map<String, String> getUserInfo(String openId) {

		String requestUrl = user_info.replace("ACCESS_TOKEN", WeixinUtil.access_token).replace("OPENID", openId);
		JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
		// 如果请求成功
		if (null != jsonObject) {
			try {
				Map<String, String> map = new HashMap<String, String>();
				map.put("openid", jsonObject.getString("openid"));
				map.put("nickname", jsonObject.getString("nickname"));
				map.put("headimgurl", jsonObject.getString("headimgurl"));
				//
				System.out.println(
						"nickname:" + jsonObject.getString("nickname") + "openid:" + jsonObject.getString("openid"));

				return map;
			} catch (JSONException e) {
				// 获取token失败
				logger.error("获取getUserInfo失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"),
						jsonObject.getString("errmsg"));
				System.out.println("获取getUserInfo失败 errcode:{} errmsg:{}" + jsonObject.getInt("errcode") + "+++++"
						+ jsonObject.getString("errmsg"));
			}
		}
		return null;
	}

	/**
	 * 
	 * @param appid
	 * @return
	 */
	public static Map<String, String> getUserInfo2(String openId, String token) {

		String requestUrl = user_info2.replace("ACCESS_TOKEN", token).replace("OPENID", openId);
		JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
		// 如果请求成功
		if (null != jsonObject) {
			try {
				Map<String, String> map = new HashMap<String, String>();
				map.put("openid", jsonObject.getString("openid"));
				map.put("nickname", jsonObject.getString("nickname"));
				map.put("headimgurl", jsonObject.getString("headimgurl"));
				//
				System.out.println(
						"nickname:" + jsonObject.getString("nickname") + "openid:" + jsonObject.getString("openid"));

				return map;
			} catch (JSONException e) {
				// 获取token失败
				logger.error("获取getUserInfo失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"),
						jsonObject.getString("errmsg"));
				System.out.println("获取getUserInfo失败 errcode:{} errmsg:{}" + jsonObject.getInt("errcode") + "+++++"
						+ jsonObject.getString("errmsg"));
			}
		}
		return null;
	}

	/**
	 * 发起https请求并获取结果
	 * 
	 * @param requestUrl
	 *            请求地址
	 * @param requestMethod
	 *            请求方式（GET、POST）
	 * @param outputStr
	 *            提交的数据
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 */
	public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
		JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();
		try {
			// 创建SSLContext对象，并使用我们指定的信任管理器初始化
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(requestUrl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);

			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			// 设置请求方式（GET/POST）
			httpUrlConn.setRequestMethod(requestMethod);

			if ("GET".equalsIgnoreCase(requestMethod))
				httpUrlConn.connect();

			// 当有数据需要提交时
			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式，防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			jsonObject = JSONObject.fromObject(buffer.toString());
		} catch (ConnectException ce) {
			logger.error("Weixin server connection timed out.");
		} catch (Exception e) {
			logger.error("https request error:{}", e);
		}
		return jsonObject;
	}

}